var count;
var result;
function unit_water(param1,param2,param3,param4,formula){
	for(var i = 1;i <= 2;i++){
		$("#sum_param"+i+"_num").empty();
		document.getElementById("input_style"+i).style.display="";
		document.getElementById("newSelect_id"+i).value = null;
		$('#newSelect_id'+i).selectpicker('refresh');
    	document.getElementById("sum_numbers"+i).style.display="none";
		$("#sum_input_num"+i).val("");
		$("#sum_param"+i+"_table").empty();
		document.getElementById("sum_sensor_select"+i).style.display="none";
		document.getElementById("work_id"+i).value = null;
		document.getElementById("select_type"+i).value = null;
		document.getElementById("select_no"+i).value = null;
		document.getElementById("sum_param"+i+"_result_group").style.display="none";
		$("#sum_param"+i+"_result_table").empty();
		document.getElementById("sum_average"+i+"_div").style.display="none";
		$("#sum_average"+i).val("");
		document.getElementById("result").style.display="none";
	}

	count = formula;	
	$.ajax({
		type : 'get',
		url : '/entity_eva_cmp_water_anl/selectResult',
		async: false,
		data:{
			'rid':label_eva_cmp_water_anl_unique_id,
            'count': count
        },
		success : function(data) {
			result = data;
		}
	});
	if(result['sumResult'] != null){
		if(result['param'] == null){
			$('#sum_param1').text(param2);
			$('#sum_param2').text(param3);
			$('#sum_bark').text(param4);
			$('#sum_title').text(param1);
			$('#count_data').modal();
			
			analyze(1);
			analyze(2);
		}else{
			if(result['param']['param1'] != null){
				$('#sum_param1').text(param2);
				$('#sum_param2').text(param3);
				$('#sum_bark').text(param4);
				$('#sum_title').text(param1);
				document.getElementById("input_style1").style.display="none";
	 		    $("#sum_param1_num").empty();
				var Oinput=document.createElement("input");
	 		    Oinput.setAttribute('id', 'param1_input');
	 		    Oinput.setAttribute('class', 'form-control');
	 		    Oinput.setAttribute('value', result['param']['param1']);
	 		    Oinput.setAttribute('readonly', 'readonly');
	 		    $("#sum_param1_num").append(Oinput); 
	 		    $('#count_data').modal();
	 		    analyze(2);
			}
			if(result['param']['param2'] != null){
				$('#sum_param1').text(param2);
				$('#sum_param2').text(param3);
				$('#sum_bark').text(param4);
				$('#sum_title').text(param1);
				document.getElementById("input_style2").style.display="none";
				$("#sum_param2_num").empty();
				var Oinput=document.createElement("input");
	 		    Oinput.setAttribute('id', 'param2_input');
	 		    Oinput.setAttribute('class', 'form-control');
	 		    Oinput.setAttribute('value', result['param']['param2']);
	 		    Oinput.setAttribute('readonly', 'readonly');
	 		    $("#sum_param2_num").append(Oinput);
	 		    $('#count_data').modal();
	 		    analyze(1);
			}
		}
		
		$("#sum0"+count).text(result['sumResult']['result']);
		document.getElementById("result").style.display="";
		$("#result_input").val(result['sumResult']['result']);
	}else if(result['sumResult'] == null){
		if(result['param'] == null){
			$('#sum_param1').text(param2);
			$('#sum_param2').text(param3);
			$('#sum_bark').text(param4);
			$('#sum_title').text(param1);
			$('#count_data').modal();
		}else{
			if(result['param']['param1'] != null){
				$('#sum_param1').text(param2);
				$('#sum_param2').text(param3);
				$('#sum_bark').text(param4);
				$('#sum_title').text(param1);
			
				document.getElementById("input_style1").style.display="none";
				$("#sum_param1_num").empty();
				var Oinput=document.createElement("input");
	 		    Oinput.setAttribute('id', 'param1_input');
	 		    Oinput.setAttribute('class', 'form-control');
	 		    Oinput.setAttribute('value', result['param']['param1']);
	 		    Oinput.setAttribute('readonly', 'readonly');
	 		    $("#sum_param1_num").append(Oinput); 
	 		    $('#count_data').modal();
	 		    
			}
			if(result['param']['param2'] != null){
				$('#sum_param1').text(param2);
				$('#sum_param2').text(param3);
				$('#sum_bark').text(param4);
				$('#sum_title').text(param1);
				document.getElementById("input_style2").style.display="none";
				$("#sum_param2_num").empty();
				var Oinput=document.createElement("input");
	 		    Oinput.setAttribute('id', 'param2_input');
	 		    Oinput.setAttribute('class', 'form-control');
	 		    Oinput.setAttribute('value', result['param']['param2']);
	 		    Oinput.setAttribute('readonly', 'readonly');
	 		    $("#sum_param2_num").append(Oinput);
	 		    $('#count_data').modal();
	 		    
			}
		}
		
	}
}

function analyze(param){
	var par;
	if(param == 1){
		par = 'one';
	}else{
		par = 'two';
	}
	if(result['sumResult'][par]['type'] == 0){
		var len = result['sumResult']['time']['startTime'].length;
		document.getElementById("newSelect_id"+param).value = 0;
		$('#newSelect_id'+param).selectpicker('refresh');
		document.getElementById("sum_numbers"+param).style.display="";
		$("#sum_input_num"+param).val(len);
		$("#sum_param"+param+"_table").empty();
		$("#sum_param"+param+"_table").append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
			  </tr>');
		for(var i = 1 ;i<=len;i++){
			$("#sum_param"+param+"_table").append('<tr>\
				    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
				    <td><input class="form-control" id="start_param'+param+i+'" type="text" readOnly="readOnly"></td>\
					<td><input class="form-control" id="end_param'+param+i+'" type="text" readOnly="readOnly"></td>\
				  </tr>')
			$("#start_param"+param+i).val(result['sumResult']['time']['startTime'][i-1]);
			$("#end_param"+param+i).val(result['sumResult']['time']['endTime'][i-1]);
		}
		document.getElementById("sum_sensor_select"+param).style.display="";//显示设备选择
		
		sensor_select(param,1,par);//后端交互设备信息
		
		document.getElementById("sum_param"+param+"_result_table").style.display="";
		$('#sum_param'+param+'_result_table').empty();
		$('#sum_param'+param+'_result_table').append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
				<th style="text-align: center; vertical-align: middle; " >差值</th>\
			  </tr>')
			  for(var i = 1 ;i<=len;i++){
					$("#sum_param1_result_table").append('<tr>\
						    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
						    <td><input class="form-control" id="re_start_param'+param+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_end_param'+param+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_delta_param'+param+i+'" type="text" readOnly="readOnly"></td>\
						  </tr>')
					$("#re_start_param"+param+i).val($("#start_param"+param+i).val());
					$("#re_end_param"+param+i).val($("#end_param"+param+i).val());
					$("#re_delta_param"+param+i).val(result['sumResult'][par]['delta'][i-1]);
				}	
		$("#sum_average"+param).val(result['sumResult'][par]['average']);
	}else if(result['sumResult'][par]['type'] == 1){
		document.getElementById("newSelect_id"+param).value = 1;
	    $('#newSelect_id'+param).selectpicker('refresh');
		document.getElementById("sum_average"+param+"_div").style.display="";//显示平均值输入框
		$("#sum_average"+param).val(result['sumResult'][par]['average']);
	}else{
		document.getElementById("input_style"+param).style.display="none";
		    $("#sum_param"+param+"_num").empty();
		var Oinput=document.createElement("input");
		    Oinput.setAttribute('id', 'param'+param+'_input');
		    Oinput.setAttribute('class', 'form-control');
		    Oinput.setAttribute('value', result['sumResult'][par]['average']);
		    Oinput.setAttribute('readonly', 'readonly');
		    $("#sum_param"+param+"_num").append(Oinput); 
	}
}

/**
 * 选择自动录入方式，以及其他包含内容
 * @param title 0-自动，1-手动
 * @returns
 */
var input_style;
function change(title,param){
	document.getElementById("sum_numbers"+param).style.display="none";
	document.getElementById("sum_average"+param+"_div").style.display="none";
	document.getElementById("sum_sensor_select"+param).style.display="none";
	$("#sum_input_num"+param).val("");
	$("#sum_param"+param+"_table").empty();
	$("#sum_average"+param).val("");
	$("#work_id"+param).val("");
	$("#select_type"+param).val("");
	$("#select_no"+param).val("");
	if(param == 1){
		input_style = title;
		if(title == 0){
			document.getElementById("sum_numbers"+param).style.display="";//显示次数 
		}else{
			document.getElementById("sum_average"+param+"_div").style.display="";//显示平均值输入框
		}
	}
	if(param == 2){
		if(input_style == 0&&title == 0){
			document.getElementById("sum_numbers"+param).style.display="";
			$("#sum_input_num2").val($("#sum_input_num1").val());
			$("#sum_input_num2").attr("readOnly","true");	
		}else if(title == 1){
			document.getElementById("sum_average2_div").style.display="";//显示平均值输入框
		}else if(title == 0){
			document.getElementById("sum_numbers"+param).style.display="";//显示次数 
		}
	}
	
	
	
}

/**
 * 点击生成 时间table，以及设备选择
 * @returns
 */
function sum_numbers_table(param){
	var title1 = $("#newSelect_id1").val();
	var title2 = $("#newSelect_id2").val();
	if(title1 == 0&&title2 == 0){
		document.getElementById("sum_param2_table").style.display="";
		var num = $("#sum_input_num2").val();
		$("#sum_param2_table").empty();
		$("#sum_param2_table").append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
			  </tr>');
		for(var i = 1 ;i<=num;i++){
			$("#sum_param2_table").append('<tr>\
				    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
				    <td><input class="form-control" id="start_param2'+i+'" type="text" readOnly="readOnly"></td>\
					<td><input class="form-control" id="end_param2'+i+'" type="text" readOnly="readOnly"></td>\
				  </tr>')
			$("#start_param2"+i).val($("#start_param1"+i).val());
			$("#end_param2"+i).val($("#end_param1"+i).val());
		}
	}else{
		document.getElementById("sum_param"+param+"_table").style.display="";
		var num = $("#sum_input_num"+param).val();
		$("#sum_param"+param+"_table").empty();
		$("#sum_param"+param+"_table").append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
			  </tr>')
		for(var i = 1 ;i<=num;i++){
			$("#sum_param"+param+"_table").append('<tr>\
				    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
				    <td><input class="form-control" id="start_param'+param+i+'" type="text" readOnly="readOnly"></td>\
					<td><input class="form-control" id="end_param'+param+i+'" type="text" readOnly="readOnly"></td>\
				  </tr>');
			$('#start_param'+param+i).val(getNowFormatDate())
		     $('#start_param'+param+i).datetimepicker({
		    	 format: "yyyy-mm-dd hh:ii:ss",
	             language: 'zh-CN',
	             todayBtn: true,
	             autoclose: true,
	             todayHighlight: 1,
	             startView: 2,
	             showMeridian: true,
	             endDate: new Date(),
		     });
			$('#end_param'+param+i).val(getNowFormatDate())
		     $('#end_param'+param+i).datetimepicker({
		    	 format: "yyyy-mm-dd hh:ii:ss",
	             language: 'zh-CN',
	             todayBtn: true,
	             autoclose: true,
	             todayHighlight: 1,
	             startView: 2,
	             showMeridian: true,
	             endDate: new Date(),
		     });
		}
	}
	
	document.getElementById("sum_sensor_select"+param).style.display="";//显示设备选择
	sensor_select(param,0);//后端交互设备信息
	
}

/**
 * 获取当前时期 yyyy-mm-dd hh:mm:ss
 * @returns
 */
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var Hours = date.getHours();
    var Minutes = date.getMinutes();
    var Seconds = date.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (Hours >= 0 && Hours <= 9) {
        Hours = "0" + Hours;
    }
    if (Minutes >= 0 && Minutes <= 9) {
        Minutes = "0" + Minutes;
    }
    if (Seconds >= 0 && Seconds <= 9) {
        Seconds = "0" + Seconds;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + Hours + seperator2 + Minutes
            + seperator2 + Seconds;
    return currentdate;
}

//selectpicker 功能完善
$('.selectpicker').selectpicker('val', 'mustard');
$('.selectpicker').selectpicker('val', [ 'mustard', 'relish' ]);
$('.selectpicker').selectpicker('refresh');

/**
 * 设备计算信息显示动态框
 * @param param 表示设备位置，是除数还是被除数，用1或2表示
 * @param flag 表示初次还是再次展示，初始为没哟计算，再次表示已经至少计算一次
 * @param par 表示返回结果是除数还是被除数的计算结果或计算参数
 * @returns 正常显示动态框
 */
function sensor_select(param,flag,par){	
	//动态加载
	//查询所有车间  
	$.ajax({
		type : 'get',
		url : '/warning_record/queryworkshop',
		async: false,
		success : function(data) {
			$('#work_id'+param).empty();
		    $("#work_id"+param).selectpicker("refresh");
			//拼接下拉框
			for (var i = 0; i < data.length; i++) {
				$("#work_id"+param).append(
						"<option value='"+data[i]+"'>" + data[i]
								+ "</option>");						
			}
			$("#work_id"+param).selectpicker("refresh");
			
		},
	});
	 //选用change事件，当对select 1选择option时都会及时响应2的结果
	 $('#work_id'+param).change(function(){
		 change_work_id(param);
	 });
	 $('#select_type'+param).change(function(){
		 change_select_type(param);
	 });
	 if(flag == 0){
			
		}else{
			$('#work_id'+param).val(result['sumResult'][par]['position']['category']);
			$('#work_id'+param).selectpicker("refresh");
			change_work_id(param);
			$('#select_type'+param).val(result['sumResult'][par]['position']['type']);
			$('#select_type'+param).selectpicker("refresh");
			change_select_type(param);
			$('#select_no'+param).val(result['sumResult'][par]['position']['sensor_id']);
			$('#select_no'+param).selectpicker("refresh");
		}
}

function change_work_id(param){
	 $('#select_type'+param).empty();
	 $("#select_type"+param).selectpicker("refresh");
	 $('#select_no'+param).empty();
	 $("#select_no"+param).selectpicker("refresh");
	//清除之前缓存数据
		var workshop_values = $("#work_id"+param).val();
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
		//根据车间查类型
		$.ajax({
			type : 'get',
			url : '/warning_record/querysortbyworkshop?'+ workshop,
			async: false,
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_type"+param).append(
							"<option value='"+data[i]+"'>"
									+ data[i] + "</option>");
				}
				$("#select_type"+param).selectpicker("refresh");
			}
		});
}
function change_select_type(param){
	 $('#select_no'+param).empty();
	 $("#select_no"+param).selectpicker("refresh");
	//清除之前缓存数据
	    var workshop_values = $("#work_id"+param).val();
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
		var sort = $("#select_type"+param).val();
		sort = 'sort='+ sort;
		//根据车间和类型查传感器编号
		$.ajax({
			type : 'get',
			url : '/warning_record/querysensorrowidbyworkshopandsort?' + workshop + '&' + sort,
			async: false,
			success : function(data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_no"+param).append(
							"<option value='"+data[i]+"'>"
									+ data[i] + "</option>");
				}
				$("#select_no"+param).selectpicker("refresh");
			}
		});			
}

//提交计算
$('#count_data_submit').on('click', function () { 
    var average1 = -1;
    var average2 = -1;
    if($("#sum_average1").val()!=""){
    	average1 = $("#sum_average1").val();
    }
    if($("#sum_average2").val()!=""){
    	average2 = $("#sum_average2").val();
    }
   if($("#param1_input").val()!=null){
    	average1 = $("#param1_input").val();
    }
    if($("#param2_input").val()!=null){
    	average2 = $("#param2_input").val();
    }
    var type1 = 2;
    var type2 = 2;
    if($("#newSelect_id1").val()!=null){
    	type1 = $("#newSelect_id1").val();
    }
    if($("#newSelect_id2").val()!=null){
    	type2 = $("#newSelect_id2").val();
    }
    var startTime = [];
    var endTime = [];
    var num;
    var param = 1;
    num = $("#sum_input_num1").val();
    if(num == ""){
    	num = $("#sum_input_num2").val();
    	param = 2;
    }
    for(var i = 1;i <= num;i++){
    	startTime.push($("#start_param"+param+i).val());
    	endTime.push($("#end_param"+param+i).val());
    }
    var category1 = -1;
    var position_type1 = -1;
    var sensor_id1 = [];
    if($("#newSelect_id1").val() == 0){
    	category1 = $("#work_id1").val();
        position_type1 = $("#select_type1").val();
        sensor_id1.push( $("#select_no1").val());
    }
    
    var category2 = -1;
    var position_type2 = -1;
    var sensor_id2 = [];
    if($("#newSelect_id2").val() == 0){
    	category2 = $("#work_id2").val();
        position_type2 = $("#select_type2").val();
        sensor_id2.push($("#select_no2").val());
    }
	var sum_result = null;
	var data = {
					'id':label_eva_cmp_water_anl_unique_id,
					'count': count,
					'one': {
							'type':type1,
							'average':average1,
							'delta':[],
							'position':{
							'category':category1,
							'type':position_type1,
							'sensor_id':sensor_id1
							}
						},
					'two': {
							'type':type2,
							'average':average2,
							'delta':[],
							'position':{
							'category':category2,
							'type':position_type2,
							'sensor_id':sensor_id2
								}
							},
					'time':{
							'startTime':startTime,
							'endTime':endTime
							},
					'result':-1
	};
	alert(JSON.stringify(data));
	$.ajax({
		type : 'post',
		url : '/entity_eva_cmp_water_anl/calculateResult',
		async: false,
		dataType : 'json',
		contentType:"application/json",
		data: JSON.stringify(data),
		success : function(data) {
			sum_result = data;
		},
		error:function(){
			 bootoast({
                 message: '失败',
                 position: 'top',
                 type: 'danger',
                 timeout: 1.5,
             });
		}
	});
	if(sum_result['one']['type'] == 0){
		document.getElementById("sum_param1_result_table").style.display="";
		$('#sum_param1_result_table').empty();
		$('#sum_param1_result_table').append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
				<th style="text-align: center; vertical-align: middle; " >差值</th>\
			  </tr>')
			  for(var i = 1 ;i<=num;i++){
					$("#sum_param1_result_table").append('<tr>\
						    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
						    <td><input class="form-control" id="re_start_param1'+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_end_param1'+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_delta_param1'+i+'" type="text" readOnly="readOnly"></td>\
						  </tr>')
					$("#re_start_param1"+i).val($("#start_param1"+i).val());
					$("#re_end_param1"+i).val($("#end_param1"+i).val());
					$("#re_delta_param1"+i).val(sum_result['one']['delta'][i-1]);
				}	
		document.getElementById("sum_average1_div").style.display="";//显示平均值输入框
		$("#sum_average1").val(sum_result['one']['average']);
	}
	if(sum_result['two']['type'] == 0){
		document.getElementById("sum_param2_result_table").style.display="";
		$('#sum_param2_result_table').empty();
		$('#sum_param2_result_table').append('<tr>\
			    <th style="text-align: center; vertical-align: middle; " >序号</th>\
			    <th style="text-align: center; vertical-align: middle; " >开始时间</th>\
				<th style="text-align: center; vertical-align: middle; " >结束时间</th>\
				<th style="text-align: center; vertical-align: middle; " >差值</th>\
			  </tr>')
			  for(var i = 1 ;i<=num;i++){
					$("#sum_param2_result_table").append('<tr>\
						    <td style="text-align: center; vertical-align: middle; ">'+i+'</td>\
						    <td><input class="form-control" id="re_start_param2'+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_end_param2'+i+'" type="text" readOnly="readOnly"></td>\
							<td><input class="form-control" id="re_delta_param2'+i+'" type="text" readOnly="readOnly"></td>\
					      </tr>')
					$("#re_start_param2"+i).val($("#start_param2"+i).val());
					$("#re_end_param2"+i).val($("#end_param2"+i).val());
					$("#re_delta_param2"+i).val(sum_result['two']['delta'][i-1]);
				}
		document.getElementById("sum_average2_div").style.display="";//显示平均值输入框
		$("#sum_average2").val(sum_result['two']['average']);
	}
	
	document.getElementById("result").style.display="";
	if (sum_result['result'] != null){
		$("#result_input").val(sum_result['result']);
		$("#sum0"+count).text(sum_result['result']);
	}
	else {
		$("#result_input").val("该范围内无数据");
		$("#sum0"+count).text("");
	}
})
